package cn.px.service.sqarepartmanage.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.px.common.util.*;
import cn.px.dao.enums.*;
import com.github.pagehelper.PageHelper;
import cn.px.common.bean.AbstractPageResultBean;
import cn.px.common.cache.ConfigCache;
import cn.px.common.constant.CommonConstants;
import cn.px.common.exception.BusinessException;
import cn.px.common.exception.DeniedException;
import cn.px.common.model.UserInfo;
import cn.px.dao.bean.MyPage;
import cn.px.dao.dto.check.CheckStandardSpareDTO;
import cn.px.dao.dto.sb.SbModelSpareBomDTO;
import cn.px.dao.dto.sqarepartmanage.SparePartInfoDTO;
import cn.px.dao.dto.sqarepartmanage.SparePartUsedDTO;
import cn.px.dao.entity.check.CheckJob;
import cn.px.dao.entity.sb.SbInfo;
import cn.px.dao.entity.sb.SbModel;
import cn.px.dao.entity.sb.SbModelSpareBom;
import cn.px.dao.entity.sqarepartmanage.SparePartInfo;
import cn.px.dao.entity.sqarepartmanage.SpareType;
import cn.px.dao.entity.store.SpareStore;
import cn.px.dao.entity.store.Store;
import cn.px.dao.entity.upms.SysFile;
import cn.px.dao.mapper.check.CheckJobMapper;
import cn.px.dao.mapper.check.CheckStandardSpareMapper;
import cn.px.dao.mapper.sb.SbInfoMapper;
import cn.px.dao.mapper.sb.SbModelMapper;
import cn.px.dao.mapper.sb.SbModelSpareBomMapper;
import cn.px.dao.mapper.sqarepartmanage.SparePartInfoMapper;
import cn.px.dao.mapper.sqarepartmanage.SparePartUsedMapper;
import cn.px.dao.mapper.sqarepartmanage.SpareTypeMapper;
import cn.px.dao.mapper.store.InStoreFormMapper;
import cn.px.dao.mapper.store.OutStoreFormMapper;
import cn.px.dao.mapper.store.SpareStoreMapper;
import cn.px.dao.mapper.store.StoreMapper;
import cn.px.dao.mapper.upms.SysFileMapper;
import cn.px.dao.util.CustomExcelImportUtil;
import cn.px.dao.util.MessageTemplateUtil;
import cn.px.dao.vo.query.check.CheckStandardSpareVO;
import cn.px.dao.vo.query.sparepartmanage.SparePartInfoVO;
import cn.px.dao.vo.query.store.StoreVO;
import cn.px.dao.vo.sb.SbInfoVO;
import cn.px.dao.vo.sb.SbModelSpareBomVO;
import cn.px.dao.vo.spare.SparePartUsedVO;
import cn.px.service.base.impl.BaseServiceImpl;
import cn.px.service.check.CheckStandardService;
import cn.px.service.event.WorkplaceBacklogEvent;
import cn.px.service.sqarepartmanage.SparePartInfoService;
import cn.px.service.util.CodeFileUtils;
import cn.px.service.util.SysFileUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import javax.persistence.Id;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 备件基础信息 service 实现类
 * @author 品讯科技
 * @date 2024-08
 * @Version Copyright (c) 2019,北京乾元坤和科技有限公司 All rights reserved.
 */
@AllArgsConstructor
@Service("sparePartInfoService")
@Slf4j
public class SparePartInfoServiceImpl extends BaseServiceImpl<SparePartInfoMapper, SparePartInfo, SparePartInfoDTO> implements SparePartInfoService {

    private final SbInfoMapper sbInfoMapper;
    private final SpareTypeMapper spareTypeMapper;
    private final SbModelMapper sbModelMapper;
    private final StoreMapper storeMapper;
    private final SbModelSpareBomMapper sbModelSpareBomMapper;
    private final SpareStoreMapper spareStoreMapper;
    private final Environment environment;
    private final SysFileMapper sysFileMapper;
    private final SparePartUsedMapper sparePartUsedMapper;
    private CheckJobMapper checkJobMapper;
    private CheckStandardSpareMapper checkStandardSpareMapper;
    private CheckStandardService checkStandardService;
    private InStoreFormMapper inStoreFormMapper;
    private OutStoreFormMapper outStoreFormMapper;




    @Override
    public AbstractPageResultBean<SparePartInfoVO> getInOrOut(SparePartInfoDTO dto, Integer pageNum, Integer pageSize) {
        List<StoreVO> stores = storeMapper.selectList(null);
        Map<String,String> map = new HashMap<>();
        for (StoreVO vo:stores){
            if (vo.getLevel()==3){
                first:for (StoreVO vo1:stores){
                    System.out.println("11111111111");
                    if (vo.getParentId().equals(vo1.getId())){
                        for (StoreVO vo2:stores){
                            System.out.println("22222222222");
                            if (vo1.getParentId().equals(vo2.getId())){
                                System.out.println("33333333333");
                                String name1 = vo2.getName().replaceAll("\\s*","").replaceAll("[^(0-9)]","");
                                String name2 = vo1.getName().replaceAll("\\s*","").replaceAll("[^(0-9)]","");
                                String name =name1+"-"+name2+"-"+vo.getName();
                                map.put(vo.getId(),name);
                                break first;
                            }
                        }
                    }
                }
            }
        }
        if(StringUtils.isNotEmpty(dto.getModel())){
            SbModelSpareBomDTO sbModelDTO = new SbModelSpareBomDTO();
            sbModelDTO.setKeyword(dto.getModel());
            List<SbModelSpareBomVO> modelList = sbModelSpareBomMapper.selectVOList(sbModelDTO);
            List<String> spareList = modelList.stream().map(item -> item.getSpareId()).distinct().collect(Collectors.toList());
            dto.setSpareIdList(spareList);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<SparePartInfoVO> sparePartInfoVOS = mapper.getInOrOut(dto);
        Set<String> ids = map.keySet();
        for (String id:ids){
            for (SparePartInfoVO vo:sparePartInfoVOS){
                if (vo.getStoreId()!=null&&vo.getStoreId().equals(id)){
                    vo.setStoreName(map.get(id));
                    continue;
                }
            }
        }
        AbstractPageResultBean<SparePartInfoVO> pageInfos = new MyPage(sparePartInfoVOS);
        return pageInfos;
    }

    @Override
    public int batchDelete(List<String> ids) {

        // 如果该类下面有仓库，且数量大于0 ，则不能删除
        Weekend<SpareStore> weekendStore = new Weekend<>(SpareStore.class);
        WeekendCriteria<SpareStore, Object> weekendCriteriaStore = weekendStore.weekendCriteria();
        weekendCriteriaStore.andIn(SpareStore::getSpareId, ids).andGreaterThan(SpareStore::getNum, 0);
        List<SpareStore> spareStoreList = spareStoreMapper.selectByExample(weekendStore);
        if (!CollectionUtils.isEmpty(spareStoreList)) {
            throw new BusinessException("该备件仓库有数据，不能删除，请先清空仓库库存");
        }
        // 删除
        Weekend<SparePartInfo> weekend = new Weekend<>(SparePartInfo.class);
        WeekendCriteria<SparePartInfo, Object> weekendCriteria = weekend.weekendCriteria();
        weekendCriteria.andIn(SparePartInfo::getId, ids);
        mapper.deleteByExample(weekend);
        return 1;
    }

    @Override
    public List<SparePartInfoVO> selectSpareInfoListByModelId(String modelId) {
        return mapper.selectSpareInfoList(modelId);
    }

    @Override
    public List<SparePartInfoVO> selectSpareInfoListBySbId(String sbId) {
        return mapper.selectSpareInfoListBySbId(sbId);
    }

    @Override
    public AbstractPageResultBean<SparePartInfoVO> selectSpareInfoPageListBySbId(String sbId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new MyPage(mapper.selectSpareInfoListBySbId(sbId));
    }

    /**
     * 定时扫描是否过期
     * 1：增加warnStatus状态
     * 增加warnStatus的枚举类型
     * 2：每周定时扫描warnStatus为正常的，判断他的最低库存是否正常，有异常的交给人工来判定。并发送邮件通知
     * 3：扫描的时候，是扫描总库存，有可能仓库里面的备件不在同一个库存。
     * <p>
     * 4：增加预警菜单，查出来所有异常的列表
     * 5：增加人工干预，可以改变每条的状态。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void genMinStockWarn() {
        SparePartInfoDTO record = new SparePartInfoDTO();
        record.setSearchMinStockWarn(true);
        // 查找超过最低库存的备件
        List<SparePartInfoVO> sparePartInfoVOList = mapper.selectPageList(record);
        List<SparePartInfo> sparePartInfos = new ArrayList<>();
        for (SparePartInfoVO sparePartInfoVO : sparePartInfoVOList) {
            SparePartInfo sparePartInfo = new SparePartInfo();
            sparePartInfo.setId(sparePartInfoVO.getId());
            sparePartInfo.setWarnStatus(1);
            sparePartInfos.add(sparePartInfo);
            mapper.updateByPrimaryKeySelective(sparePartInfo);
        }

        if (!CollectionUtils.isEmpty(sparePartInfos)) {
            // 发送邮件通知
            String email = ConfigCache.getLabelByValueAllowNull(SysConfigEnum.SPARE_WARN_EMAIL.name());
            String domain = ConfigCache.getLabelByValueAllowNull(SysConfigEnum.SYSTEM_DOMAIN.name());
            String url = ConfigCache.getLabelByValueAllowNull(SysConfigEnum.URL_SPARE_MIN_STOCK_WARN.name());
            if (StringUtils.isNotBlank(email)) {
                // 通过给邮件人员
                SpringContextHolder.publishEvent(new WorkplaceBacklogEvent(WorkplaceBacklogTypeEnum.CHECK_SPARE_WARN.getValue(), WorkplaceBacklogDetailTypeEnum.CHECK_SPARE_WARN.getValue(),
                        null, MessageTemplateUtil.getSpareMinStockWarnNotice(domain + url, sparePartInfos.size()),
                        null, null, Arrays.asList(email)));
            }
        }
    }

    /**
     * 定时扫描是否过期
     * 1：增加warnStatus状态
     * 增加warnStatus的枚举类型
     * 2：每周定时扫描warnStatus为正常的，判断他的最低库存是否正常，有异常的交给人工来判定。并发送邮件通知
     * 3：扫描的时候，是扫描总库存，有可能仓库里面的备件不在同一个库存。
     * <p>
     * 4：增加预警菜单，查出来所有异常的列表
     * 5：增加人工干预，可以改变每条的状态。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void genCheckStockWarn() {

        // 查询近六个月待执行的任务列表。
        LocalDate now = LocalDate.now();
        LocalDate afterSixMonth = DateUtils.plus(now, 6, ChronoUnit.MONTHS);
        Weekend<CheckJob> weekend = new Weekend<>(CheckJob.class);
        weekend.weekendCriteria().andNotEqualTo(CheckJob::getStatus, CheckJobStatusEnum.FINISHED.getValue())
                .andBetween(CheckJob::getStartTime, now, afterSixMonth);
        List<CheckJob> checkJobs = checkJobMapper.selectByExample(weekend);
        // 获取未执行的标准id，不能用stream获取id列表，会覆盖重复的标准id(不会重复，因为一个标准对应一个任务。)
        List<CheckStandardSpareVO> voList = new ArrayList<CheckStandardSpareVO>();
        if(CollectionUtil.isNotEmpty(checkJobs)){
            List<String> ids = checkJobs.stream().map(CheckJob::getStandardId).collect(Collectors.toList());
            ids = ids.stream().filter(item -> StringUtils.isNotBlank(item)).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(ids) && ids.size()>0) {
                CheckStandardSpareDTO dto = new CheckStandardSpareDTO();
                dto.setCheckIds(ids);
                voList = checkStandardSpareMapper.selectSpareWarn(dto);

                // 判断总库存是否大于最近6个月的需求量
                if(CollectionUtil.isNotEmpty(voList)){
                    for(CheckStandardSpareVO checkStandardSpareVO:voList){
                        if(checkStandardSpareVO.getNum().compareTo(checkStandardSpareVO.getStoreNum())>0){
                            SparePartInfo sparePartInfo = new SparePartInfo();
                            sparePartInfo.setId(checkStandardSpareVO.getId());
                            sparePartInfo.setForecastStatus(1);
                            mapper.updateByPrimaryKeySelective(sparePartInfo);
                        }
                    }

                    // 发送邮件通知
                    String email = ConfigCache.getLabelByValueAllowNull(SysConfigEnum.SPARE_WARN_EMAIL.name());
                    String domain = ConfigCache.getLabelByValueAllowNull(SysConfigEnum.SYSTEM_DOMAIN.name());
                    String url = ConfigCache.getLabelByValueAllowNull(SysConfigEnum.URL_SPARE_CHECK_STOCK_WARN.name());
                    if (StringUtils.isNotBlank(email)) {
                        // 通过给邮件人员
                        SpringContextHolder.publishEvent(new WorkplaceBacklogEvent(WorkplaceBacklogTypeEnum.CHECK_SPARE_WARN.getValue(), WorkplaceBacklogDetailTypeEnum.CHECK_SPARE_WARN.getValue(),
                                null, MessageTemplateUtil.getSpareCheckStockWarnNotice(domain + url, voList.size()),
                                null, null, Arrays.asList(email)));
                    }

                }
            }
        }
    }

    @Override
    public List<SparePartInfo> getByIds(List<String> ids) {
        Weekend<SparePartInfo> weekend = new Weekend<>(SparePartInfo.class);
        weekend.weekendCriteria().andIn(SparePartInfo::getId, ids);
        List<SparePartInfo> list = mapper.selectByExample(weekend);
        List<SpareType> spareTypes = spareTypeMapper.selectAll();
        for (SparePartInfo vo : list) {
            if (StringUtils.isBlank(vo.getQrCode())) {
                // 保存二维码
                String path = CommonConstants.RESOURCE_PREFIX + "/png/" + DateUtil.formatDate(new Date()) + "/" + IdGeneratorUtils.getObjectId() + "/";
                String rootPath = environment.getProperty("upload.root-dir");
                String filePath = rootPath + path;
                String codePath = path + vo.getId() + ".png";
                CodeFileUtils.uploadFileECode(vo.getId(), rootPath, filePath, vo.getId() + ".png");
                // 修改二维码
                SparePartInfoDTO sbInfoDTO = new SparePartInfoDTO();
                sbInfoDTO.setId(vo.getId());
                sbInfoDTO.setQrCode(codePath);
                vo.setQrCode(codePath);
                this.updateQrCode(sbInfoDTO);

            }

            if (vo.getTypeId() != null) {
                spareTypes.forEach(spareType -> {
                    if (spareType.getId().equals(vo.getTypeId())) {
                        vo.setTypeName(spareType.getName());
                        return;
                    }
                });
            }
        }
        Collections.sort(list, new Comparator<SparePartInfo>() {
            @Override
            public int compare(SparePartInfo o1, SparePartInfo o2) {
                return o1.getNo().compareTo(o2.getNo());
            }
        });
        return list;
    }

    public static void main(String[] args) {
        String ss = "TYPJ-CC-00002";
        String newStr = ss.substring(ss.length() - 5);
        int count = Integer.valueOf(newStr) + 1;
        String str1 = String.format("%05d", count);
        System.out.println(str1);
    }

    @Override
    public List<SparePartInfo> getModelListByDTO(SparePartInfoDTO sparePartInfoDTO) {
        if (sparePartInfoDTO.getTypeId() != null) {
            Weekend<SpareType> weekend = new Weekend<>(SpareType.class);
            WeekendCriteria<SpareType, Object> weekendCriteria = weekend.weekendCriteria();
            weekendCriteria.andEqualTo(SpareType::getParentId, sparePartInfoDTO.getTypeId());
            List<SpareType> childList = spareTypeMapper.selectByExample(weekend);
            List<String> typeIds = new ArrayList<String>();
            typeIds.add(sparePartInfoDTO.getTypeId());
            if (!CollectionUtils.isEmpty(childList)) {
                childList.forEach(item -> {
                    typeIds.add(item.getId());
                });
            }
            sparePartInfoDTO.setTypeIds(typeIds);
        }
        if (sparePartInfoDTO.getTypeId() != null) {
            Weekend<SpareType> weekend = new Weekend<>(SpareType.class);
            WeekendCriteria<SpareType, Object> weekendCriteria = weekend.weekendCriteria();
            weekendCriteria.andEqualTo(SpareType::getParentId, sparePartInfoDTO.getTypeId());
            List<SpareType> childList = spareTypeMapper.selectByExample(weekend);
            List<String> typeIds = new ArrayList<String>();
            typeIds.add(sparePartInfoDTO.getTypeId());
            if (!CollectionUtils.isEmpty(childList)) {
                childList.forEach(item -> {
                    typeIds.add(item.getId());
                });
            }
            sparePartInfoDTO.setTypeIds(typeIds);
        }
        List<SparePartInfoVO> listVO = mapper.selectPageList(sparePartInfoDTO);
        List<SpareType> typeList = spareTypeMapper.selectAll();
        for (SparePartInfoVO vo : listVO) {
            for (SpareType type : typeList) {
                if (StringUtils.isNotBlank(vo.getTypeId()) && vo.getTypeId().equals(type.getId())) {
                    vo.setTypeName(type.getName());
                    vo.setTypeNo(type.getNo());
                }
                if (StringUtils.isNotBlank(vo.getParentTypeId()) && vo.getParentTypeId().equals(type.getId())) {
                    vo.setParentName(type.getName());
                    vo.setParentNo(type.getNo());
                }
                if (StringUtils.isNotBlank(vo.getMiddleTypeId()) && vo.getMiddleTypeId().equals(type.getId())) {
                    vo.setMiddleName(type.getName());
                    vo.setMiddleNo(type.getNo());
                }
                if (StringUtils.isNotBlank(vo.getChildTypeId()) && vo.getChildTypeId().equals(type.getId())) {
                    vo.setChildName(type.getName());
                    vo.setChildNo(type.getNo());
                }
            }
        }
        List<SparePartInfo> list = BeanConverterUtil.copyListProperties(listVO, SparePartInfo.class);
        list.sort(Comparator.comparing(SparePartInfo::getName));
        return list;
    }

    private List<SparePartInfoVO> getSparePartInfoVOS(List<SparePartInfoVO> sparePartInfoVOS){
        List<StoreVO> stores = storeMapper.selectList(null);
        Map<String,String> map = new HashMap<>();
        for (StoreVO vo:stores){
            if (vo.getLevel()==3){
                first:for (StoreVO vo1:stores){
                    System.out.println("11111111111");
                    if (vo.getParentId().equals(vo1.getId())){
                        for (StoreVO vo2:stores){
                            System.out.println("22222222222");
                            if (vo1.getParentId().equals(vo2.getId())){
                                System.out.println("33333333333");
                                String name1 = vo2.getName().replaceAll("\\s*","").replaceAll("[^(0-9)]","");
                                String name2 = vo1.getName().replaceAll("\\s*","").replaceAll("[^(0-9)]","");
                                String name =name1+"-"+name2+"-"+vo.getName();
                                map.put(vo.getId(),name);
                                break first;
                            }
                        }
                    }
                }
            }
        }
        Set<String> ids = map.keySet();
        for (String id:ids){
            for (SparePartInfoVO vo:sparePartInfoVOS){
                if (vo.getStoreId()!=null&&vo.getStoreId().equals(id)){
                    vo.setStoreName(map.get(id));
                    continue;
                }
            }
        }
        return sparePartInfoVOS;
    }

    private void addSbRelationShip(SparePartInfoDTO sparePartInfoDTO,List<SparePartInfoVO> list) {
        // 查询备件关联的设备型号信息
        List<SbModelSpareBomVO> bomList = sbModelSpareBomMapper.selectExportList2(sparePartInfoDTO);
        for (SparePartInfoVO sparePartInfo : list) {
//                if (sparePartInfo.getYt()==1){
//                    sparePartInfo.setYtStr("设备配件");
//                }else if (sparePartInfo.getYt()==2){
//                    sparePartInfo.setYtStr("工程物资");
//                }else {
//                    sparePartInfo.setYtStr("设备配件");
//                }
            StringBuffer sb = new StringBuffer();
            for (SbModelSpareBomVO sbModelSpareBomVO : bomList) {
                if (sparePartInfo.getId().equals(sbModelSpareBomVO.getSpareId())) {

                    SbInfo sbInfo = new SbInfo();
                    sbInfo.setId(sbModelSpareBomVO.getSbId());
                    sbInfo = sbInfoMapper.selectOne(sbInfo);
                    sb = sb.append(sbInfo.getNo()).append(';');
//                    sparePartInfo.setModelName(sbModelSpareBomVO.getName());
//                    sparePartInfo.setModelModel(sbModelSpareBomVO.getModel());
//                        sparePartInfo.setSbNo(sb.append(sbInfo.getNo())+";");
                }
            }
            sparePartInfo.setSbNo(sb.toString());
        }
    }

    @Override
    public SparePartInfoVO getSpareInfoVOById(String id) {
        SparePartInfoVO vo = mapper.getSpareInfoVOById(id);
        String finalName = "";
        if (vo.getStoreId()!=null) {
            List<String> names = new ArrayList<>();
            names = getFinalStoreName(vo.getStoreId(), names);
            if (names.size() == 3) {
                finalName = names.get(2).replaceAll("\\s*","").replaceAll("[^(0-9)]","")
                        +"-"+names.get(1).replaceAll("\\s*","").replaceAll("[^(0-9)]","")
                        +"-"+names.get(0);
            }else {
                for (int i = names.size() - 1; i >= 0; i--) {
                    finalName = finalName + "-" + names.get(i);
                    finalName = finalName.substring(1);
                }
            }
        }
        vo.setStoreName(finalName);
        return vo;
    }
    private List<String> getFinalStoreName(String id,List<String> names){
        Store store = storeMapper.selectByPrimaryKey(id);
        if (store!=null) {
            names.add(store.getName());
            if (store.getParentId() != null&&!store.getParentId().trim().equals("")) {
                getFinalStoreName(store.getParentId(),names);
            }
        }
        return names;
    }


    @Override
    public AbstractPageResultBean<SparePartInfoVO> selectPageInfo2(SparePartInfoDTO record, int pageNum, int pageSize) {

        if(StringUtils.isNotEmpty(record.getModel())){
            SbModelSpareBomDTO sbModelDTO = new SbModelSpareBomDTO();
            sbModelDTO.setKeyword(record.getModel());
            List<SbModelSpareBomVO> modelList = sbModelSpareBomMapper.selectVOList(sbModelDTO);
            List<String> spareList = modelList.stream().map(item -> item.getSpareId()).distinct().collect(Collectors.toList());
            record.setSpareIdList(spareList);
        }

        // 选择设备对应的备件bom列表
        if (record.getSbId() != null) {
            SbInfoVO sbInfo = sbInfoMapper.getById(record.getSbId());
            List<SparePartInfoVO> partList = mapper.selectSpareInfoList(sbInfo.getModelId());
            PageHelper.startPage(pageNum, pageSize);
//            List<SparePartInfoVO> partList = mapper.selectSpareInfoList(sbInfo.getModelId());
            AbstractPageResultBean<SparePartInfoVO> pageInfo = new MyPage(partList);
            return pageInfo;
        } else {
            List<SpareType> typeList = spareTypeMapper.selectAll();
            if (StringUtils.isNotBlank(record.getTypeName())) {
                for (SpareType type : typeList) {
                    if (type.getName().equals(record.getTypeName())) {
                        record.setTypeId(type.getId());
                        break;
                    }
                }
            }
            if (record.getTypeId() != null) {
                Weekend<SpareType> weekend = new Weekend<>(SpareType.class);
                WeekendCriteria<SpareType, Object> weekendCriteria = weekend.weekendCriteria();
                weekendCriteria.andEqualTo(SpareType::getParentId, record.getTypeId());
                List<SpareType> childList = spareTypeMapper.selectByExample(weekend);
                List<String> typeIds = new ArrayList<String>();
                typeIds.add(record.getTypeId());
                if (!CollectionUtils.isEmpty(childList)) {
                    childList.forEach(item -> {
                        typeIds.add(item.getId());
                    });
                }
                record.setTypeIds(typeIds);
            }

            PageHelper.startPage(pageNum, pageSize);
            List<SparePartInfoVO> list = mapper.selectPageList(record);
            for (SparePartInfoVO vo : list) {
                for (SpareType type : typeList) {
                    if (StringUtils.isNotBlank(vo.getTypeId()) && vo.getTypeId().equals(type.getId())) {
                        vo.setTypeName(type.getName());
                        vo.setTypeNo(type.getNo());
                    }
                    if (StringUtils.isNotBlank(vo.getParentTypeId()) && vo.getParentTypeId().equals(type.getId())) {
                        vo.setParentName(type.getName());
                        vo.setParentNo(type.getNo());
                    }
                    if (StringUtils.isNotBlank(vo.getMiddleTypeId()) && vo.getMiddleTypeId().equals(type.getId())) {
                        vo.setMiddleName(type.getName());
                        vo.setMiddleNo(type.getNo());
                    }
                    if (StringUtils.isNotBlank(vo.getChildTypeId()) && vo.getChildTypeId().equals(type.getId())) {
                        vo.setChildName(type.getName());
                        vo.setChildNo(type.getNo());
                    }
                }
            }
            getSparePartInfoVOS(list);
            addSbRelationShip(null,list);
            AbstractPageResultBean<SparePartInfoVO> pageInfo = new MyPage(list);
            return pageInfo;
        }
    }

    @Override
    public SparePartInfo getModelById(Object id) {
        SparePartInfo model = mapper.selectById(id);
        List<String> ids = new ArrayList<String>();
        if (StringUtils.isNotBlank(model.getTypeId()) && !ids.contains(model.getTypeId())) {
            ids.add(model.getTypeId());
        }
        if (StringUtils.isNotBlank(model.getParentTypeId()) && !ids.contains(model.getParentTypeId())) {
            ids.add(model.getParentTypeId());
        }
        if (StringUtils.isNotBlank(model.getMiddleTypeId()) && !ids.contains(model.getMiddleTypeId())) {
            ids.add(model.getMiddleTypeId());
        }
        if (StringUtils.isNotBlank(model.getChildTypeId()) && !ids.contains(model.getChildTypeId())) {
            ids.add(model.getChildTypeId());
        }
        Weekend<SpareType> weekend = new Weekend<>(SpareType.class);
        WeekendCriteria<SpareType, Object> weekendCriteria = weekend.weekendCriteria();
        weekendCriteria.andIn(SpareType::getId, ids);
        List<SpareType> typeList = spareTypeMapper.selectByExample(weekend);
        for (SpareType type : typeList) {
            if (StringUtils.isNotBlank(model.getTypeId()) && model.getTypeId().equals(type.getId())) {
                model.setTypeName(type.getName());
            }
            if (StringUtils.isNotBlank(model.getParentTypeId()) && model.getParentTypeId().equals(type.getId())) {
                model.setParentName(type.getName());
                model.setParentNo(type.getNo());
            }
            if (StringUtils.isNotBlank(model.getMiddleTypeId()) && model.getMiddleTypeId().equals(type.getId())) {
                model.setMiddleName(type.getName());
                model.setMiddleNo(type.getNo());
            }
            if (StringUtils.isNotBlank(model.getChildTypeId()) && model.getChildTypeId().equals(type.getId())) {
                model.setChildName(type.getName());
                model.setChildNo(type.getNo());
            }
        }
       /* Weekend<SysFile> weekendFile = new Weekend<>(SysFile.class);
        weekendFile.weekendCriteria().andEqualTo(SysFile::getTargetId, model.getId());
        List<SysFile> sysFiles = sysFileMapper.selectByExample(weekendFile);
        List<SysFile> s = ListUtils.newArrayList();
        List<SysFile> applicationFileList = ListUtils.newArrayList();
        sysFiles.forEach(item -> {
            if (item.getType().equals(SysFileTypeEnum.SPARE_IMGS.getValue())) {
                applicationFileList.add(item);
            }
        });
        model.setApplicationFileList(applicationFileList);*/

        return model;
    }

    /**
     * 新增同时入了仓库，所以初始数量须填写一下，不填则默认为0
     *
     * @param model
     * @return
     */
    @Override
    public SparePartInfo saveModelByDTO(SparePartInfoDTO model) {

        // 设置备件的统一编号
        SpareType parentType = spareTypeMapper.selectByPrimaryKey(model.getParentTypeId());
        SpareType middleType = spareTypeMapper.selectByPrimaryKey(model.getMiddleTypeId());
        String parentTypeNo = "";
        String middleTypeNo = "";
        if (parentType != null) {
            parentTypeNo = parentType.getNo();
            model.setParentNo(parentTypeNo);
        }
        if (middleType != null) {
            middleTypeNo = middleType.getNo();
            model.setMiddleNo(middleTypeNo);
        }
        if(model.getMinStock() == null){
            model.setMinStock(new BigDecimal(0));
        }
        if(model.getMaxStock() == null){
            model.setMaxStock(new BigDecimal(0));
        }
        String nameNo = model.getNameNo();
        String ggNo = model.getGgNo();
        String childTypeNo = null;
        if (StringUtils.isNotBlank(model.getChildTypeId())) {
            SpareType childType = spareTypeMapper.selectByPrimaryKey(model.getChildTypeId());
            childTypeNo = childType.getNo();
            model.setChildNo(childTypeNo);
            model.setTypeId(model.getChildTypeId());
            model.setUniteNo(parentTypeNo + "-" + middleTypeNo + "-" + childTypeNo);
        } else {
            if (StringUtils.isNotBlank(model.getMiddleTypeId())) {
                model.setTypeId(model.getMiddleTypeId());
                model.setUniteNo(parentTypeNo + "-" + middleTypeNo);
            } else {
                model.setTypeId(model.getParentTypeId());
                model.setUniteNo(parentTypeNo);
            }
        }

        Weekend<SparePartInfo> weekend = new Weekend<>(SparePartInfo.class);
        weekend.weekendCriteria().andEqualTo(SparePartInfo::getName, model.getName()).andEqualTo(SparePartInfo::getGgxh, model.getGgxh());
        int checkInfo = mapper.selectCountByExample(weekend);
        if (checkInfo > 0) {
            throw new BusinessException("同名称同规格的备件已存在，请重新设置");
        }
        model.setId(IdGeneratorUtils.getObjectId());

        // 设置编码
        setSpareNo(model);

        // 保存二维码
        String path = CommonConstants.RESOURCE_PREFIX + "/png/" + DateUtil.formatDate(new Date()) + "/" + IdGeneratorUtils.getObjectId() + "/";
        String rootPath = environment.getProperty("upload.root-dir");
        String filePath = rootPath + path;
        String codePath = path + model.getId() + ".png";
        model.setQrCode(codePath);
        CodeFileUtils.uploadFileECode(model.getId(), rootPath, filePath, model.getId() + ".png");

        UserInfo userInfo = SecurityUtils.getUserInfo();
        LocalDateTime time = LocalDateTime.now();
        // 如果由sbId,则要创建bom
        if (StringUtils.isNotBlank(model.getSbId())) {
            SbModelSpareBom bom = new SbModelSpareBom();
            bom.setId(IdGeneratorUtils.getObjectId());
            bom.setSpareId(model.getId());
            bom.setNum(new BigDecimal(1));
            bom.setCreatedTime(time);
            bom.setCreatedUserId(userInfo.getUserId());
            bom.setPeriod(1);
            bom.setPeriodType(1);
            bom.setSbId(model.getSbId());
            bom.setUpdateTime(time);
            bom.setUpdateUserId(userInfo.getUserId());
            sbModelSpareBomMapper.insert(bom);
        }
        //this.saveFile(model);

        // 如果初始化数量有了，就需要更新库存
        if (model.getInitStock() == null) {
            model.setInitStock(new BigDecimal(0));
        }
        if (model.getInitStock() != null) {
            SpareStore spareStore = new SpareStore();
            spareStore.setSpareId(model.getId());
            spareStore.setId(IdGeneratorUtils.getObjectId());
//            if (StringUtils.isBlank(model.getStoreId())) {
//                throw new BusinessException("请设置库位信息");
//            }
            if (StringUtils.isNotBlank(model.getStoreId())) {
                Store store = storeMapper.selectByPrimaryKey(model.getStoreId());
                if (store == null) {
                    throw new BusinessException("找不到仓库，请重新选择");
                }
                if (StoreLevelEnum.ZONGCANG.getValue().equals(store.getLevel())) {
                    throw new BusinessException("备件不可放到总仓，请具体到库位");
                }
                spareStore.setStoreId(model.getStoreId());
            }
            BigDecimal price = model.getInitialValue();
            spareStore.setPrice(model.getInitialValue());
            spareStore.setNum(model.getInitStock());
            spareStore.setInitNum(model.getInitStock());
            spareStore.setInitPrice(model.getInitialValue());
            spareStore.setInitPurchasePrice(model.getInitialValue());
            spareStore.setCreatedTime(time);
            spareStore.setCreatedUserId(userInfo.getUserId());
            spareStore.setUpdateTime(time);
            spareStore.setUpdateUserId(userInfo.getUserId());
            spareStoreMapper.insert(spareStore);
        }

        // 插入设备关联
        List<SbModelSpareBomDTO> detailList = model.getDetailList();
        if (!CollectionUtils.isEmpty(detailList)) {
            for (SbModelSpareBomDTO detail : detailList) {
                detail.setSpareId(model.getId());
                detail.setId(IdGeneratorUtils.getObjectId());
            }
            sbModelSpareBomMapper.insertListforComplex(BeanConverterUtil.copyListProperties(detailList, SbModelSpareBom.class));
        }
        return super.saveModelHaveCreateInfo(model);
    }

    public void setSpareNo(SparePartInfoDTO model) {
        String prefix = "";
        SpareType spareType = spareTypeMapper.selectByPrimaryKey(model.getTypeId());
        if (StringUtils.isNotBlank(spareType.getParentId())) {
            SpareType spareType1 = spareTypeMapper.selectByPrimaryKey(spareType.getParentId());
            prefix += spareType1.getNo() + "-";
        }
        prefix += spareType.getNo() + "-";
        String selectMaxNo = mapper.selectMaxNo(model.getTypeId());
        if (StringUtils.isBlank(selectMaxNo)) {
            model.setNo(prefix + "00001");
        } else {
            String newStr = selectMaxNo.substring(selectMaxNo.length() - 5).replaceFirst("^0*", "");
            int count = Integer.valueOf(newStr) + 1;
            String str1 = String.format("%05d", count);
            model.setNo(prefix + str1);
        }
    }

    @Override
    public void updateSpareNo(SparePartInfo model) {
        String prefix = "";
        SpareType spareType = spareTypeMapper.selectByPrimaryKey(model.getTypeId());
        if(spareType == null){
            throw new BusinessException("备件类别不存在：type_id=" + model.getTypeId());
        }
        if (StringUtils.isNotBlank(spareType.getParentId())) {
            SpareType spareType1 = spareTypeMapper.selectByPrimaryKey(spareType.getParentId());
            prefix += spareType1.getNo() + "-";
        }
        prefix += spareType.getNo() + "-";
        String selectMaxNo = mapper.selectMaxNo(model.getTypeId());
        if (StringUtils.isBlank(selectMaxNo)) {
            model.setNo(prefix + "00001");
        } else {
            log.info("selectMaxNo: " + selectMaxNo);
            String newStr = selectMaxNo.substring(selectMaxNo.length() - 5).replaceFirst("^0*", "");
            int count = Integer.valueOf(newStr) + 1;
            String str1 = String.format("%05d", count);
            model.setNo(prefix + str1);
        }
        SparePartInfo sparePartInfo = new SparePartInfo();
        sparePartInfo.setId(model.getId());
        sparePartInfo.setNo(model.getNo());
        mapper.updateByPrimaryKeySelective(sparePartInfo);

    }

    @Override
    public void modModelByDTO(SparePartInfoDTO model) {

        UserInfo userInfo = SecurityUtils.getUserInfo();
        LocalDateTime time = LocalDateTime.now();
        // 设置备件的统一编号
        SpareType parentType = spareTypeMapper.selectByPrimaryKey(model.getParentTypeId());
        SpareType middleType = spareTypeMapper.selectByPrimaryKey(model.getMiddleTypeId());
        String parentTypeNo = "";
        String middleTypeNo = "";
        if (parentType != null) {
            parentTypeNo = parentType.getNo();
            model.setParentNo(parentTypeNo);
        }
        if (middleType != null) {
            middleTypeNo = middleType.getNo();
            model.setMiddleNo(middleTypeNo);
        }
        String nameNo = model.getNameNo();
        String ggNo = model.getGgNo();
        String childTypeNo = null;
        if (StringUtils.isNotBlank(model.getChildTypeId())) {
            SpareType childType = spareTypeMapper.selectByPrimaryKey(model.getChildTypeId());
            childTypeNo = childType.getNo();
            model.setChildNo(childTypeNo);
            model.setTypeId(model.getChildTypeId());
            model.setUniteNo(parentTypeNo + "-" + middleTypeNo + "-" + childTypeNo + "-" + nameNo + "-" + ggNo);
        } else {
            model.setTypeId(model.getMiddleTypeId());
            if (StringUtils.isNotBlank(middleTypeNo)) {
                model.setTypeId(model.getMiddleTypeId());
                model.setUniteNo(parentTypeNo + "-" + middleTypeNo);
            } else {
                model.setTypeId(model.getParentTypeId());
                model.setUniteNo(parentTypeNo);
            }
        }

        Weekend<SparePartInfo> weekend = new Weekend<>(SparePartInfo.class);
        weekend.weekendCriteria().andEqualTo(SparePartInfo::getName, model.getName()).andEqualTo(SparePartInfo::getGgxh, model.getGgxh());
        int count = mapper.selectCountByExample(weekend);
        if (count > 1) {
            throw new BusinessException("同名称同规格的备件已存在，请重新设置名称或者规格");
        }

        // 插入设备关联
        List<SbModelSpareBomDTO> detailList = model.getDetailList();
        List<SbModelSpareBomDTO> addList = new ArrayList<SbModelSpareBomDTO>();
        List<SbModelSpareBomDTO> updateList = new ArrayList<SbModelSpareBomDTO>();

        // 先删后插,前端删除的不存在与ids里面，说明被删掉了，需要删除
        Weekend<SbModelSpareBom> detailWeekend = new Weekend<>(SbModelSpareBom.class);
        List<String> ids = detailList.stream().map(SbModelSpareBomDTO::getId).collect(Collectors.toList());
        ids = ids.stream().filter(item -> StringUtils.isNotBlank(item)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(ids) && ids.size() > 0) {
            detailWeekend.weekendCriteria().andNotIn(SbModelSpareBom::getId, ids).andEqualTo(SbModelSpareBom::getSpareId, model.getId());
            sbModelSpareBomMapper.deleteByExample(detailWeekend);
        } else {
            // 全部刪除:说明id为空，全部删除了
            detailWeekend.weekendCriteria().andEqualTo(SbModelSpareBom::getSpareId, model.getId());
            sbModelSpareBomMapper.deleteByExample(detailWeekend);
        }
        // 新增与更新
        if (!CollectionUtils.isEmpty(detailList)) {
            for (SbModelSpareBomDTO detail : detailList) {
                if (StringUtils.isBlank(detail.getId())) {
                    detail.setSpareId(model.getId());
                    detail.setId(IdGeneratorUtils.getObjectId());
                    addList.add(detail);
                } else {
                    updateList.add(detail);
                }
            }
            if (!CollectionUtils.isEmpty(addList)) {
                sbModelSpareBomMapper.insertListforComplex(BeanConverterUtil.copyListProperties(addList, SbModelSpareBom.class));
            }
            if (!CollectionUtils.isEmpty(updateList)) {
                sbModelSpareBomMapper.updateBatchAll(BeanConverterUtil.copyListProperties(updateList, SbModelSpareBom.class));
            }
        }
        //修改关联仓库
        if (model.getStoreId()!=null){
            SpareStore spareStore = new SpareStore();
            spareStore.setSpareId(model.getId());
            spareStoreMapper.delete(spareStore);
            spareStore.setStoreId(model.getStoreId());
            setKey2(spareStore);
            spareStoreMapper.insert(spareStore);
        }
        // this.saveFile(model);
        super.modModelByDTO(model);
    }

    private void saveFile(SparePartInfoDTO model) {
        if (CollectionUtil.isNotEmpty(model.getApplicationFileList())) {
            Weekend<SysFile> weekend = new Weekend<>(SysFile.class);
            weekend.weekendCriteria().andEqualTo(SysFile::getType, SysFileTypeEnum.SPARE_IMGS.getValue()).andEqualTo(SysFile::getTargetId, model.getId());
            sysFileMapper.deleteByExample(weekend);
            List<SysFile> list = SysFileUtils.changeFileList(model.getApplicationFileList(), model.getId(), SysFileTypeEnum.SPARE_IMGS.getValue());
            if (CollectionUtil.isNotEmpty(list)) {
                sysFileMapper.insertListforComplex(list);
            }
        }
    }

    /**
     * 导入备件基础信息
     *
     * @param file
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String importListByAddAA(MultipartFile file) {
        int addNum = 0;
        List<String> modelExist = new ArrayList<String>();
        List<SparePartInfoVO> addItems = new ArrayList<SparePartInfoVO>();
        List<String> modelError = new ArrayList<String>();
        List<String> modelWarn = new ArrayList<String>();
        LocalDateTime now = LocalDateTime.now();
        try {
            List<SparePartInfoVO> items = CustomExcelImportUtil.importSparePartInfoList(now, file.getInputStream());
            if (!CollectionUtils.isEmpty(items)) {

                List<SparePartInfo> vos = mapper.selectAll();
                List<SparePartInfo> addItemsReal = new ArrayList<SparePartInfo>();
                List<SbModel> modelList = sbModelMapper.selectAll();
                List<SpareType> typeList = spareTypeMapper.selectAll();
                List<SbModelSpareBom> bomList = new ArrayList<SbModelSpareBom>();
                List<SpareStore> spareStoreList = new ArrayList<SpareStore>();
                List<String> modelIdsWithBom = new ArrayList<String>();
                List<SbModel> addSbModelItems = new ArrayList<SbModel>();
                for (SparePartInfoVO item : items) {
                    System.out.println("正在处理:" + item.getName() + ",编号" + item.getNo());
                    boolean isExist = false;
                    for (SparePartInfo old : vos) {
                        // System.out.println("正在对比:" + old.getName() + ", 规格" + old.getGgxh() + ", 原厂编号" + old.getInitNo());
                        if (item.getGgxh() == null) {
                            if (old.getName().equals(item.getName()) && old.getGgxh() == null) {
                                isExist = true;
                                item.setId(old.getId());
                                item.setNo(old.getNo());
                                item.setInitNo(old.getInitNo());
                                if (!modelExist.contains(item.getName() + "，规格" + item.getGgxh())) {
                                    modelExist.add(item.getName() + "，规格" + item.getGgxh());
                                }
                            }
                        } else {
                            if (old.getGgxh() == null) {

                            } else {
                                if (old.getName().equals(item.getName()) && old.getGgxh().equals(item.getGgxh())) {
                                    isExist = true;
                                    item.setId(old.getId());
                                    item.setNo(old.getNo());
                                    item.setInitNo(old.getInitNo());
                                    if (!modelExist.contains(item.getName() + "，规格" + item.getGgxh())) {
                                        modelExist.add(item.getName() + "，规格" + item.getGgxh());
                                    }
                                }
                            }
                        }
                    }
                    // 如果已经存在，则跳过去下一个，不行，需要获取id，因为要入库。需要备件信息
                    System.out.println("处理到这");
                    if (isExist) {

                    } else {
                        // 新增的，需要设置id和类别
                        item.setId(IdGeneratorUtils.getObjectId());
                        // 设置类型转换
                        for (SpareType type : typeList) {
                            if (type.getName().equals(item.getParentName())) {
                                item.setParentTypeId(type.getId());
                                item.setParentNo(type.getNo());
                            }
                            if (type.getName().equals(item.getMiddleName())) {
                                item.setMiddleTypeId(type.getId());
                                item.setMiddleNo(type.getNo());
                            }
                            if (type.getName().equals(item.getChildName())) {
                                item.setChildTypeId(type.getId());
                                item.setChildNo(type.getNo());
                            }
                        }
                        if (StringUtils.isNotBlank(item.getChildTypeId())) {
                            item.setTypeId(item.getChildTypeId());
                        } else {
                            item.setTypeId(item.getMiddleTypeId());
                        }
                    }

                    // 设置型号bom
                    boolean findModel = false;
                    if (StringUtils.isNotBlank(item.getSbModel())) {
                        SbModelSpareBom bom = new SbModelSpareBom();
                        bom.setSpareId(item.getId());
                        for (SbModel model : modelList) {
                            if (model.getModel().equals(item.getSbModel())) {
                                findModel = true;
                                // 判断该model是否已经有bom，如果有，则不导入，需要验证后重新导入。
                                boolean withBoms = false;
                                for (String modelIdWithBom : modelIdsWithBom) {
                                    if (model.getId().equals(modelIdWithBom)) {
                                        withBoms = true;
                                        if (!modelWarn.contains(item.getSbName() + "，型号" + item.getSbModel())) {
                                            modelWarn.add(item.getSbName() + "，型号" + item.getSbModel());
                                        }
                                        break;
                                    }
                                }

                                if (withBoms) {
                                    break;
                                }
                                bom.setId(IdGeneratorUtils.getObjectId());
                                bom.setModelId(model.getId());
                                bom.setNum(new BigDecimal(1));
                                bom.setCreatedTime(now);
                                bom.setCreatedUserId("1");
                                bom.setUpdateTime(now);
                                bom.setUpdateUserId("1");
                                break;
                            }
                        }
                        if (!findModel) {
                            if (!modelError.contains(item.getSbName() + "，型号" + item.getSbModel())) {
                                modelError.add(item.getSbName() + "，型号" + item.getSbModel());
                            }
                            SbModel model = new SbModel();
                            model.setModel(item.getSbModel());
                            model.setName(item.getSbName());
                            model.setNameModel(item.getSbName() + item.getSbModel());
                            model.setUnit("台");
                            model.setValue(100000.00);
                            model.setLevel(1);
                            model.setProducerId("60004942159c0d5c6a472d6d");
                            model.setUseType(1);
                            model.setStatus(1);
                            model.setTypeId("1");
                            model.setCreatedTime(now);
                            model.setCreatedUserId("1");
                            model.setUpdateTime(now);
                            model.setUpdateUserId("1");
                            model.setRemark("备件导入新增，需要校准");
                            model.setId(IdGeneratorUtils.getObjectId());
                            boolean withModelBoms = false;
                            for (SbModel modelIs : addSbModelItems) {
                                if (modelIs.getName().equals(model.getName()) && modelIs.getModel().equals(model.getModel())) {
                                    withModelBoms = true;
                                    break;
                                }
                            }
                            if (!withModelBoms) {
                                addSbModelItems.add(model);
                            }
                            bom.setId(IdGeneratorUtils.getObjectId());
                            bom.setModelId(model.getId());
                            bom.setNum(new BigDecimal(1));
                            bom.setCreatedTime(now);
                            bom.setCreatedUserId("1");
                            bom.setUpdateTime(now);
                            bom.setUpdateUserId("1");
                            bomList.add(bom);
                        } else {
                            bomList.add(bom);
                        }
                    }

                    // 设置库存,还是从库存里面走，但是如果名称一样怎么办，还是需要从这里走
                    SpareStore spareStore = new SpareStore();
                    spareStore.setSpareId(item.getId());
                    spareStore.setId(IdGeneratorUtils.getObjectId());
                    spareStore.setStoreId(item.getStoreId());
                    spareStore.setPrice(new BigDecimal(item.getInitialValue()));
                    spareStore.setNum(item.getNum());
                    spareStore.setInitNum(item.getNum());
                    spareStore.setInitPrice(spareStore.getPrice());
                    spareStore.setInitPurchasePrice(spareStore.getPrice());
                    spareStore.setCreatedTime(now);
                    spareStore.setCreatedUserId("1");
                    spareStore.setUpdateTime(now);
                    spareStore.setUpdateUserId("1");
                    spareStoreList.add(spareStore);
                    if (!isExist) {
                        addItems.add(item);
                    }
                }

                if (modelWarn.size() > 0) {
                    System.out.println("如下型号已经存在bom，该备件没有导入，后期可以自行导入: " + modelWarn.toString());
                }
                if (!CollectionUtils.isEmpty(addItems)) {
                    addItemsReal = BeanConverterUtil.copyListProperties(addItems, SparePartInfo.class);
                    mapper.insertListforComplex(addItemsReal);
                }
                if (!CollectionUtils.isEmpty(addSbModelItems)) {
                    sbModelMapper.insertListforComplex(addSbModelItems);
                }
                if (!CollectionUtils.isEmpty(bomList)) {
                    sbModelSpareBomMapper.insertListforComplex(bomList);
                }
                if (!CollectionUtils.isEmpty(spareStoreList)) {
                    spareStoreMapper.insertListforComplex(spareStoreList);
                }
            }
            return "总计新增导入：" + (addItems.size()) + "已存在未导入数量：" + modelExist.size() + "，找不到如下型号，已经添加：" + modelError.toString();
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * 导入备件基础信息
     *
     * @param file
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importListByAdd(MultipartFile file) {
        int addNum = 0;
        List<String> modelExist = new ArrayList<String>();
        List<SparePartInfoVO> addItems = new ArrayList<SparePartInfoVO>();
        List<String> modelError = new ArrayList<String>();
        List<String> modelWarn = new ArrayList<String>();
        LocalDateTime now = LocalDateTime.now();
        try {
            List<SparePartInfoVO> items = CustomExcelImportUtil.importSparePartInfoList(now, file.getInputStream());
            if (!CollectionUtils.isEmpty(items)) {
                List<SparePartInfo> addItemsReal = new ArrayList<SparePartInfo>();
                List<SpareType> typeList = spareTypeMapper.selectAll();
                List<SpareStore> spareStoreList = new ArrayList<SpareStore>();
                for (SparePartInfoVO item : items) {
                    // 新增的，需要设置id和类别
                    item.setId(IdGeneratorUtils.getObjectId());
                    // 设置类型转换
                    for (SpareType type : typeList) {
                        if (type.getName().equals(item.getParentName())) {
                            item.setParentTypeId(type.getId());
                            item.setParentNo(type.getNo());
                        }
                        if (type.getName().equals(item.getMiddleName())) {
                            item.setMiddleTypeId(type.getId());
                            item.setMiddleNo(type.getNo());
                        }
                        if (type.getName().equals(item.getChildName())) {
                            item.setChildTypeId(type.getId());
                            item.setChildNo(type.getNo());
                        }
                    }
                    if (StringUtils.isNotBlank(item.getChildTypeId())) {
                        item.setTypeId(item.getChildTypeId());
                    } else {
                        item.setTypeId(item.getMiddleTypeId());
                    }

                    // 设置型号bom
                    /*boolean findModel = false;
                    if(StringUtils.isNotBlank(item.getSbModel())){
                        SbModelSpareBom bom = new SbModelSpareBom();
                        bom.setSpareId(item.getId());
                        for (SbModel model : modelList) {
                            if(model.getModel().equals(item.getSbModel())){
                                findModel = true;
                                bom.setId(IdGeneratorUtils.getObjectId());
                                bom.setModelId(model.getId());
                                bom.setNum(new BigDecimal(1));
                                bom.setCreatedTime(now);
                                bom.setCreatedUserId("1");
                                bom.setUpdateTime(now);
                                bom.setUpdateUserId("1");
                                break;
                            }
                        }
                        // 需要新增型号信息
                        if(!findModel){
                            if(!modelError.contains(item.getSbName() + "，型号" + item.getSbModel())){
                                modelError.add(item.getSbName() + "，型号" + item.getSbModel());
                            }
                            SbModel model = new SbModel();
                            model.setModel(item.getSbModel());
                            model.setName(item.getSbName());
                            model.setNameModel(item.getSbName() + item.getSbModel());
                            model.setUnit("台");
                            model.setValue(100000.00);
                            model.setLevel(1);
                            model.setProducerId("60004942159c0d5c6a472d6d");
                            model.setUseType(1);
                            model.setStatus(1);
                            model.setTypeId("1");
                            model.setCreatedTime(now);
                            model.setCreatedUserId("1");
                            model.setUpdateTime(now);
                            model.setUpdateUserId("1");
                            model.setRemark("备件导入新增，需要校准");
                            model.setId(IdGeneratorUtils.getObjectId());
                            boolean withModelBoms = false;
                            for (SbModel modelIs : addSbModelItems) {
                                if(modelIs.getName().equals(model.getName()) && modelIs.getModel().equals(model.getModel())){
                                    withModelBoms = true;
                                    break;
                                }
                            }
                            if(!withModelBoms){
                                addSbModelItems.add(model);
                            }
                            bom.setId(IdGeneratorUtils.getObjectId());
                            bom.setModelId(model.getId());
                            bom.setNum(new BigDecimal(1));
                            bom.setCreatedTime(now);
                            bom.setCreatedUserId("1");
                            bom.setUpdateTime(now);
                            bom.setUpdateUserId("1");
                            bomList.add(bom);
                        }else{
                            bomList.add(bom);
                        }
                    }*/

                    // 设置库存,还是从库存里面走，但是如果名称一样怎么办，还是需要从这里走
                    SpareStore spareStore = new SpareStore();
                    spareStore.setSpareId(item.getId());
                    spareStore.setId(IdGeneratorUtils.getObjectId());
                    spareStore.setStoreId(item.getStoreId());
                    BigDecimal price = new BigDecimal(item.getInitialValue());
                    spareStore.setPrice(new BigDecimal(item.getInitialValue()));
                    spareStore.setNum(new BigDecimal(0));
                    spareStore.setInitNum(new BigDecimal(0));
                    spareStore.setInitPrice(new BigDecimal(0));
                    spareStore.setInitPurchasePrice(new BigDecimal(0));
                    spareStore.setCreatedTime(now);
                    spareStore.setCreatedUserId("1");
                    spareStore.setUpdateTime(now);
                    spareStore.setUpdateUserId("1");
                    spareStoreList.add(spareStore);
                    addItems.add(item);

                }
                if (!CollectionUtils.isEmpty(addItems)) {
                    addItemsReal = BeanConverterUtil.copyListProperties(addItems, SparePartInfo.class);
                    mapper.insertListforComplex(addItemsReal);
                }
               /* if(!CollectionUtils.isEmpty(addSbModelItems)){
                    sbModelMapper.insertListforComplex(addSbModelItems);
                }
                if(!CollectionUtils.isEmpty(bomList)){
                    sbModelSpareBomMapper.insertListforComplex(bomList);
                }*/
                if (!CollectionUtils.isEmpty(spareStoreList)) {
                    spareStoreMapper.insertListforComplex(spareStoreList);
                }
            }
            return "总计新增导入：" + (addItems.size());
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }
    private List<String> getSbNos(String str){
        List<String> list = new ArrayList<>();
        if (StringUtils.isNotBlank(str)){
          list = Arrays.asList( str.trim().split(";"));
        }
        return list;
    }

    private void setKey2(Object t) {
        Field[] fields = t.getClass().getDeclaredFields();
        for (Field field : fields) {
            Annotation id = field.getAnnotation(Id.class);
            if (id == null) {
                continue;
            }
            try {
                field.setAccessible(true);
                field.set(t, IdGeneratorUtils.getObjectId());
            } catch (IllegalAccessException e) {
                log.error("主键赋值异常");
            }
        }
    }

    @Override
    public String importListByUpdate(MultipartFile file) {
        int addNum = 0;
        List<SparePartInfoVO> addItems = new ArrayList<SparePartInfoVO>();
        LocalDateTime now = LocalDateTime.now();
        try {
            List<SparePartInfoVO> items = CustomExcelImportUtil.importSparePartInfoListForUpdate(file.getInputStream());
            if (!CollectionUtils.isEmpty(items)) {
                List<SpareType> typeList = spareTypeMapper.selectAll();
                for (SparePartInfoVO item : items) {
                    //先删除当前备件的所有bom，再新增excel导入的bom
                    SbModelSpareBom bom = new SbModelSpareBom();
                    bom.setSpareId(item.getId());
                    sbModelSpareBomMapper.delete(bom);
                    List<String> sbNos = new ArrayList<>();
                    if (item.getSbNo()!=null){
                        sbNos = getSbNos(item.getSbNo());
                    }
                    if (sbNos.size()>0) {
                        Weekend<SbInfo> weekend = new Weekend<>(SbInfo.class);
                        WeekendCriteria<SbInfo, Object> weekendCriteria = weekend.weekendCriteria();
                        weekendCriteria.andIn(SbInfo::getNo, sbNos);
                        List<SbInfo> sbinfos = sbInfoMapper.selectByExample(weekend);
                        List<SbModelSpareBom> boms = new ArrayList<>();
                        for (SbInfo info : sbinfos) {
                            bom = new SbModelSpareBom();
                            bom.setSpareId(item.getId());
                            bom.setSbId(info.getId());
                            setKey2(bom);
                            bom.setCreatedTime(LocalDateTime.now());
                            bom.setCreatedUserId(SecurityUtils.getUserInfo().getUserId());
                            bom.setUpdateTime(LocalDateTime.now());
                            bom.setUpdateUserId(SecurityUtils.getUserInfo().getUserId());
                            bom.setCreatedUserName(SecurityUtils.getUserInfo().getUsername());
                            bom.setUpdateUserName(SecurityUtils.getUserInfo().getUsername());
                            boms.add(bom);
                        }
                        sbModelSpareBomMapper.insertListforComplex(boms);
                    }
                    // 设置类型转换
                    for (SpareType type : typeList) {
                        if (type.getName().equals(item.getTypeName())) {
                            item.setParentTypeId(type.getId());
                            item.setParentNo(type.getNo());
                            item.setTypeId(type.getId());
                        }
                        /*if (type.getName().equals(item.getMiddleName()) && StringUtils.isNotBlank(type.getParentId()) && type.getParentId().equals(item.getParentTypeId())) {
                            item.setMiddleTypeId(type.getId());
                            item.setMiddleNo(type.getNo());
                            item.setTypeId(type.getId());
                        }
                        if (type.getName().equals(item.getChildName()) && StringUtils.isNotBlank(type.getParentId()) && type.getParentId().equals(item.getMiddleTypeId())) {
                            item.setChildTypeId(type.getId());
                            item.setChildNo(type.getNo());
                            item.setTypeId(type.getId());
                        }*/
                    }
                    mapper.updateByPrimaryKeySelective(BeanConverterUtil.copyObjectProperties(item, SparePartInfo.class));
                    addItems.add(item);
                }
            }
            if (!CollectionUtils.isEmpty(addItems)) {
                // mapper.updateBatch(addItems);
            }
            return "总计修改：" + addItems.size();
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }

    @Override
    public void updateSpareIdsBatch(String spareId, List<String> ids) {
        Weekend<SpareStore> weekend = new Weekend<>(SpareStore.class);
        WeekendCriteria<SpareStore, Object> weekendCriteria = weekend.weekendCriteria();
        weekendCriteria.andIn(SpareStore::getSpareId, ids);
        List<SpareStore> list = spareStoreMapper.selectByExample(weekend);
        list.forEach(item -> {
            item.setSpareId(spareId);
        });
        List<SpareStore> newlist = new ArrayList<SpareStore>();
        for (SpareStore spareStore : list) {
            SpareStore spare = new SpareStore();
            spare.setId(spareStore.getId());
            spare.setSpareId(spareId);
            newlist.add(spare);
        }

        // 修改设备管理的bom备件id
        Weekend<SbModelSpareBom> weekend2 = new Weekend<>(SbModelSpareBom.class);
        WeekendCriteria<SbModelSpareBom, Object> weekendCriteria2 = weekend2.weekendCriteria();
        weekendCriteria2.andIn(SbModelSpareBom::getSpareId, ids);
        List<SbModelSpareBom> sbModelSpareBomList = sbModelSpareBomMapper.selectByExample(weekend2);
        sbModelSpareBomList.forEach(item -> {
            item.setSpareId(spareId);
        });
        List<SbModelSpareBom> newSbModelSpareBomList = new ArrayList<SbModelSpareBom>();
        for (SbModelSpareBom spareStore : sbModelSpareBomList) {
            SbModelSpareBom spare = new SbModelSpareBom();
            spare.setId(spareStore.getId());
            spare.setSpareId(spareId);
            newSbModelSpareBomList.add(spare);
        }
        sbModelSpareBomMapper.updateBatch(newSbModelSpareBomList);
        this.batchDelete(ids);
    }

    @Override
    public void updateSpareWarnStatus(String id, Integer type, Integer warnStatus) {
        SparePartInfo sparePartInfo = mapper.selectById(id);
        if (type == 1) {
            sparePartInfo.setWarnStatus(warnStatus);
        } else {
            sparePartInfo.setForecastStatus(warnStatus);
        }
        mapper.updateByPrimaryKey(sparePartInfo);
    }

    @Override
    public void updateQrCode(SparePartInfoDTO model) {
        SparePartInfo sbInfo = new SparePartInfo();
        sbInfo.setId(model.getId());
        sbInfo.setQrCode(model.getQrCode());
        mapper.updateByPrimaryKeySelective(sbInfo);
    }

    @Override
    public void generateQrCodeAll() {
        List<SparePartInfo> list = mapper.selectAll();
        for (SparePartInfo vo : list) {
            // 保存二维码
            String path = CommonConstants.RESOURCE_PREFIX + "/png/" + DateUtil.formatDate(new Date()) + "/" + vo.getId() + "/";
            String rootPath = environment.getProperty("upload.root-dir");
            String filePath = rootPath + path;
            String codePath = path + vo.getId() + ".png";
            CodeFileUtils.uploadFileECode(vo.getId(), rootPath, filePath, vo.getId() + ".png");
            // 修改二维码
            SparePartInfoDTO sbInfoDTO = new SparePartInfoDTO();
            sbInfoDTO.setId(vo.getId());
            sbInfoDTO.setQrCode(codePath);
            vo.setQrCode(codePath);
            this.updateQrCode(sbInfoDTO);
        }
    }

    /**
     * 更新备件图片
     * @param sparePartInfoDTO
     */
    @Override
    public void modImagesByDTO(SparePartInfoDTO sparePartInfoDTO) {
        SparePartInfo sparePartInfo = new SparePartInfo();
        sparePartInfo.setId(sparePartInfoDTO.getId());
        sparePartInfo.setImage(sparePartInfoDTO.getImage());
        mapper.updateByPrimaryKeySelective(sparePartInfo);
    }

    @Override
    public AbstractPageResultBean<SparePartInfoVO> getSpareList(SparePartInfoDTO record, int pageNum, int pageSize) {
        // 根据设备ID判断
        if(StringUtils.isBlank(record.getSbId())){
            // 走基础备件信息
            record.setIsSpecial(0);
        }
        PageHelper.startPage(pageNum, pageSize);
        AbstractPageResultBean<SparePartInfoVO> pageInfos = new MyPage(mapper.getSpareListBySbInfo(record));
        if(record.getUsedSource() == null){
            throw new DeniedException("请求数据，请注明备件使用场景！");
        }
        if(record.getUsedSource() == SparePartUsedSourceEnum.POLLING_CHECK.getValue()){
            // 保养，关联使用记录
            if(pageInfos != null && pageInfos.getRows() != null && pageInfos.getRows().size() > 1){
                SparePartUsedDTO queryDTO = new SparePartUsedDTO();
                queryDTO.setSbId(record.getSbId());
                for(SparePartInfoVO vo : pageInfos.getRows()){
                    queryDTO.setSpareId(vo.getId());
                    SparePartUsedVO usedVO = sparePartUsedMapper.selectSpecialOne(queryDTO);
                    if(usedVO != null){
                        vo.setUsedStatus(usedVO.getStatus());
                        vo.setStartDate(usedVO.getStartDate());
                        vo.setChangeDate(usedVO.getChangeDate());
                    }
                }
            }
        }
        return pageInfos;
    }
}
